//
//  NSString+Extension.m
//  Project
//
//  Created by 郑键 on 17/1/11.
//  Copyright © 2017年 zhengjian. All rights reserved.
//

#import "NSString+Extension.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (Extension)


#pragma mark - Base64

/**
 *  base64编码
 *
 *  @return 编码后的字符串
 */
- (NSString *)ex_base64Encode
{
    NSData *data                                = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

/**
 *  base64解码
 *
 *  @return 解码后的字符串
 */
- (NSString *)ex_base64Decode
{
    NSData *data                                = [[NSData alloc] initWithBase64EncodedString:self options:0];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

#pragma mark - Extension

/**
 *  根据正则表达式验证当前字符串
 *
 *  @param regularExpression 正则表达式
 *  @return 是否符合标准
 */
- (BOOL)ex_checkStringWithRegularExpression:(NSString *)regularExpression
{
    NSPredicate *pred                           = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regularExpression];
    return [pred evaluateWithObject:self];
}

/**
 *  验证邮箱
 *
 *  @return YES or NO
 */
- (BOOL)ex_isEmail
{
    return [self ex_checkStringWithRegularExpression:REGULAREXPRESSION_ISMAIL];
}

/**
 *  验证密码
 *
 *  @return YES or NO
 */
- (BOOL)ex_isPassword
{
    return [self ex_checkStringWithRegularExpression:REGULAREXPRESSION_ISPWD];
}

/**
 *  验证数字
 *
 *  @return YES or NO
 */
- (BOOL)ex_isRealNumbers
{
    return [self ex_checkStringWithRegularExpression:REGULAREXPRESSION_ISNUM];
}

/**
 *  验证手机号码
 *
 *  @return YES or NO
 */
- (BOOL)ex_isMobileNumber
{   
    NSPredicate *regextestmobile        = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",REGULAREXPRESSION_PHONENUMBER_MOBILE];
    NSPredicate *regextestcm            = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",REGULAREXPRESSION_PHONENUMBER_CM];
    NSPredicate *regextestcu            = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",REGULAREXPRESSION_PHONENUMBER_CU];
    NSPredicate *regextestct            = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",REGULAREXPRESSION_PHONENUMBER_CT];
    NSPredicate *regextestXNHM          = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",REGULAREXPRESSION_PHONENUMBER_XNHM];
    NSPredicate *regextestPHS           = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",REGULAREXPRESSION_PHONENUMBER_PHS];
    
    if (([regextestmobile evaluateWithObject:self]  == YES)
        || ([regextestcm evaluateWithObject:self]   == YES)
        || ([regextestct evaluateWithObject:self]   == YES)
        || ([regextestcu evaluateWithObject:self]   == YES)
        || ([regextestXNHM evaluateWithObject:self] == YES)
        || ([regextestPHS evaluateWithObject:self]  == YES)){
        return YES;
    }else{
        return NO;
    }
}

/**
 *  控制输入不含特殊符号(能够输入汉字、字母、数字)
 *
 *  @return YES or NO
 */
- (BOOL)ex_isTrueStr
{
    return [self ex_checkStringWithRegularExpression:REGULAREXPRESSION_ISSTR];
}

/**
 *  验证身份证号
 *
 *  @return YES or NO
 */
- (BOOL)ex_validateIdentityCard
{
    return [self ex_checkStringWithRegularExpression:REGULAREXPRESSION_IDENTITYCARD];
}

#pragma mark - string

/**
 *  是否包涵子字符串
 *
 *  @param subString 传入的字符串
 *
 *  @return YES or NO
 */
- (BOOL)ex_isContainSubString:(NSString *)subString
{
    if([self rangeOfString:subString].location != NSNotFound){
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - Hash Md5

/**
 *  md5
 *
 *  @return md5后的字符串
 */
- (NSString *)ex_md5String
{
    const char *str                 = self.UTF8String;
    int length                      = (int)strlen(str);
    unsigned char bytes[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, length, bytes);
    return [self ex_stringFromBytes:bytes length:CC_MD5_DIGEST_LENGTH];
}

/**
 *  sha1
 *
 *  @return sha1后的字符串
 */
- (NSString *)ex_sha1String
{
    const char *str                 = self.UTF8String;
    int length                      = (int)strlen(str);
    unsigned char bytes[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(str, length, bytes);
    return [self ex_stringFromBytes:bytes length:CC_SHA1_DIGEST_LENGTH];
}

/**
 *  sha256
 *
 *  @return sha256后的字符串
 */
- (NSString *)ex_sha256String
{
    const char *str                 = self.UTF8String;
    int length                      = (int)strlen(str);
    unsigned char bytes[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(str, length, bytes);
    return [self ex_stringFromBytes:bytes length:CC_SHA256_DIGEST_LENGTH];
}

/**
 *  sha512
 *
 *  @return sha512后的字符串
 */
- (NSString *)ex_sha512String
{
    const char *str                 = self.UTF8String;
    int length                      = (int)strlen(str);
    unsigned char bytes[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512(str, length, bytes);
    return [self ex_stringFromBytes:bytes length:CC_SHA512_DIGEST_LENGTH];
}

- (NSString *)ex_stringFromBytes:(unsigned char *)bytes length:(int)length
{
    NSMutableString *strM = [NSMutableString string];
    
    for (int i = 0; i < length; i++) {
        [strM appendFormat:@"%02x", bytes[i]];
    }
    
    return [strM copy];
}

#pragma mark - ToolMethod

/**
 *  计算富文本字体高度
 *
 *  @param lineSpace  行间距
 *  @param font       字体
 *  @param width      字体所占宽度
 *
 *  @return 富文本高度
 */
-(CGFloat)ex_getSpaceLabelHeightwithSpeace:(CGFloat)lineSpace
                                  withFont:(UIFont*)font
                                 withWidth:(CGFloat)width
{
    NSMutableParagraphStyle *paraStyle          = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineSpacing                       = lineSpace;
    NSDictionary *dic                           = @{NSFontAttributeName:font,
                                                    NSParagraphStyleAttributeName:paraStyle,
                                                    NSKernAttributeName:@1.5f};
    CGSize size                                 = [self boundingRectWithSize:CGSizeMake(width,MAXFLOAT)
                                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                                  attributes:dic
                                                                     context:nil].size;
    return size.height;
}

/**
 *  计算label的尺寸
 *
 *  @param label label
 *
 *  @return 文字所占的尺寸
 */
+ (CGSize)ex_sizeWithLabel:(UILabel *)label
{
    NSString *text                              = label.text;
    if (text == nil) text                       = @"字体";
    return [NSString ex_sizeWithText:text
                             andFont:label.font
                          andMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
}

/**
 *  文字的内容、字体大小 计算文字所占的尺寸
 *
 *  @param text    文字内容
 *  @param font    文字字体
 *
 *  @return 文字所占的尺寸
 */
+ (CGSize)ex_sizeWithText:(NSString *)text
                  andFont:(UIFont *)font
{
    return [NSString ex_sizeWithText:text
                             andFont:font
                          andMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
}

/**
 *  根据文字的内容、字体大小、最大尺寸范围 计算文字所占的尺寸
 *
 *  @param text    文字内容
 *  @param font    文字字体
 *  @param maxSize 最大尺寸范围
 *
 *  @return 文字所占的尺寸
 */
+ (CGSize)ex_sizeWithText:(NSString *)text
                  andFont:(UIFont *)font
               andMaxSize:(CGSize)maxSize
{
    CGSize expectedLabelSize                    = CGSizeZero;
    NSMutableParagraphStyle *paragraphStyle     = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode                = NSLineBreakByWordWrapping;
    [paragraphStyle setLineSpacing:0];
    NSDictionary *attributes                    = @{NSFontAttributeName:font,
                                                    NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    expectedLabelSize                           = [text boundingRectWithSize:maxSize
                                                                     options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                                  attributes:attributes
                                                                     context:nil].size;
    
    return CGSizeMake(ceil(expectedLabelSize.width), ceil(expectedLabelSize.height));
}

/**
 *  将字典、数组 转换为json字符串
 *
 *  @param object 字典、数组
 *
 *  @return 转换为json字符串
 */
+ (NSString *)ex_jsonStringWithObject:(id)object
{
    NSError *error                              = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if ([jsonData length] != 0 && error == nil) {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    } else {
        return nil;
    }
}

/**
 *  字符串替换
 *
 *  @param stringToBeChanged     要替换的字符串
 *  @param stringToBeChangedWith 替换字符串
 *  @param oldStr                原始字符串
 *
 *  @return 替换后的字符串
 */
+ (NSString *)ex_replaceOldStr:(NSString *)stringToBeChanged
                       withStr:(NSString *)stringToBeChangedWith
                    withString:(NSString *)oldStr{
    NSString *newStr                            = [oldStr stringByReplacingOccurrencesOfString:stringToBeChanged
                                                                                    withString:stringToBeChangedWith];
    return newStr;
}


@end
